package com.tongtech.space.controller.common;

import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.tongtech.space.common.constants.Constants;
import com.tongtech.space.common.pojo.Result;
import com.tongtech.space.common.utils.TisRequest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 公共controller
 *
 * @author jiayu
 * @since 2020/12/14
 */
@Slf4j
@RestController
@RequestMapping(Constants.URL_API_VERSION + "/public")
@Api(tags = "公共接口(无需登录)")
public class PublicController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
	@Autowired
	private TisRequest tisRequest;

    @ApiOperation(value = "健康检查接口(检查redis与mysql,status为true则连接正常)")
    @PostMapping("/health-check")
    public Result healthCheck() {
        try {
            // 检查redis
            redisTemplate.opsForValue().set("healthCheck", "ok", 1, TimeUnit.SECONDS);
        } catch (Exception e) {
            return Result.fail("服务器异常!异常信息为:" + e.getMessage());
        }

        return Result.success();
    }

    @ApiOperation(value = "Tis下载")
	@GetMapping(value = "/download", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public void download(HttpServletRequest request, HttpServletResponse response,@RequestParam(value="fileId") String fileId,@RequestParam(value="fileName") String fileName) {

		if (StringUtils.isBlank(fileId)) {
			PrintWriter writer = null;
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html; charset=utf-8");
			try {
				writer = response.getWriter();
				String ret = "下载失败";
				writer.print(ret);
			} catch (Exception e) {
				log.error(e.getMessage());
			}
		}
			tisRequest.doDownLoad(fileId, fileName, request, response);
    }

}
